package com.weihui.jxc.view;

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Toolkit;

import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import java.awt.BorderLayout;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import com.weihui.jxc.common.CommonFactory;
import com.weihui.jxc.common.ValidationManager;
import com.weihui.jxc.model.Customer;
import com.weihui.jxc.model.GoodsInfo;
import com.weihui.jxc.model.InAndOut;
import com.weihui.jxc.model.Item;
import com.weihui.jxc.model.Provider;
import com.weihui.jxc.service.GoodsService;
import com.weihui.jxc.service.InportService;
import com.weihui.jxc.service.ProviderService;

import java.awt.FlowLayout;
import javax.swing.JComboBox;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import java.awt.event.ActionEvent;

/**
 * 进货单
 * 
 * @author FPF
 *
 */
public class InportInternalFrame extends JInternalFrame implements ActionListener {
	// 获取屏幕尺寸
	Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
	private JTextField idTf;
	private JTextField conTf;
	private JTextField timeTf;
	private JTextField sponTf;
	private MyTableModel tableModel;// 自定义的表格模板，为了适配数据
	private JTable table;// 表格一定要放在JScrollPane，这样数据多的时候，就可以滑动表格
	private JTextField numberTf;
	private JTextField priceTf;
	private JTextField comTf;
	private JTextField operTf;
	JComboBox comboBox_1;// 结算方式
	JComboBox comboBox;// 供应商
	Item providerItem;// 供应商Item
	private ProviderService providerService;
	private GoodsService goodsService;
	private InportService inportService;
	private Float price;// 商品单价
	private String goodsId;//商品编号

	/**
	 * 初始化视窗
	 */
	public InportInternalFrame() {
		super("进货单", true, true, true, true);
		setBounds(0, 0, screenSize.width * 2 / 3, screenSize.height * 2 / 3);

		JPanel panel = new JPanel();
		getContentPane().add(panel, BorderLayout.NORTH);

		JPanel panel_1 = new JPanel();

		JPanel panel_2 = new JPanel();

		JPanel panel_3 = new JPanel();
		// 创建表格的列（标题栏文字）
		// 创建表格的列（标题栏文字）
		String[] columnNames = { "商品ID", "商品全称", "商品简称", "商品产地", "商品规格", "商品包装", "商品批号", "批准文号", "商品价格", "商品备注",
				"供应商全称" };
		// 实例化模板
		tableModel = new MyTableModel<GoodsInfo>(columnNames, GoodsInfo.class);
		// 创建表格面板
		table = new JTable(tableModel);
		// 表格行改变时监听
		table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

			@Override
			public void valueChanged(ListSelectionEvent e) {
				ListSelectionModel model = (ListSelectionModel) e.getSource();
				int index = model.getMaxSelectionIndex();
				// 对index进行验证
				if (index == -1) {
					return;
				}
				price = (Float) table.getValueAt(index, 8);//商品价格
				goodsId = (String) table.getValueAt(index, 0);//商品编号
				System.out.println(table.getValueAt(index, 0) + "," + price);// 测试id和商品价格
			}
		});
		;
		// 设置表格的大小
		table.setPreferredScrollableViewportSize(new Dimension(screenSize.width * 2 / 3 - 60, screenSize.height / 3));
		// 视图高度填充
		table.setFillsViewportHeight(true);
		table.setAutoCreateRowSorter(true);

		// 将表格放到滑动面板中
		JScrollPane scrollPane = new JScrollPane(table);
		panel_3.add(scrollPane);

		JPanel panel_4 = new JPanel();

		JPanel panel_5 = new JPanel();

		JPanel panel_6 = new JPanel();
		GroupLayout gl_panel = new GroupLayout(panel);
		gl_panel.setHorizontalGroup(gl_panel.createParallelGroup(Alignment.TRAILING).addGroup(gl_panel
				.createSequentialGroup().addContainerGap()
				.addGroup(gl_panel.createParallelGroup(Alignment.TRAILING)
						.addComponent(panel_6, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 1236, Short.MAX_VALUE)
						.addComponent(panel_5, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 1236, Short.MAX_VALUE)
						.addComponent(panel_4, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 1236, Short.MAX_VALUE)
						.addComponent(panel_3, GroupLayout.DEFAULT_SIZE, 1236, Short.MAX_VALUE)
						.addComponent(panel_2, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 1236, Short.MAX_VALUE)
						.addComponent(panel_1, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 1236, Short.MAX_VALUE))
				.addContainerGap()));
		gl_panel.setVerticalGroup(gl_panel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel.createSequentialGroup().addGap(5)
						.addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
						.addComponent(panel_2, GroupLayout.PREFERRED_SIZE, 43, GroupLayout.PREFERRED_SIZE).addGap(3)
						.addComponent(panel_3, GroupLayout.PREFERRED_SIZE, 165, GroupLayout.PREFERRED_SIZE).addGap(3)
						.addComponent(panel_4, GroupLayout.PREFERRED_SIZE, 49, GroupLayout.PREFERRED_SIZE).addGap(3)
						.addComponent(panel_5, GroupLayout.PREFERRED_SIZE, 43, GroupLayout.PREFERRED_SIZE).addGap(3)
						.addComponent(panel_6, GroupLayout.PREFERRED_SIZE, 45, GroupLayout.PREFERRED_SIZE)
						.addContainerGap()));

		JButton btnNewButton = new JButton("入库");
		btnNewButton.addActionListener(this);
		panel_6.add(btnNewButton);

		JButton btnNewButton_1 = new JButton("确认");
		btnNewButton_1.addActionListener(this);
		panel_6.add(btnNewButton_1);

		JLabel lblNewLabel_8 = new JLabel("验收结论：");
		panel_5.add(lblNewLabel_8);

		comTf = new JTextField();
		panel_5.add(comTf);
		comTf.setColumns(25);

		JLabel lblNewLabel_9 = new JLabel("操作人员：");
		panel_5.add(lblNewLabel_9);

		operTf = new JTextField();
		operTf.setEditable(false);
		panel_5.add(operTf);
		operTf.setColumns(25);

		JLabel lblNewLabel_6 = new JLabel("商品数量：");
		panel_4.add(lblNewLabel_6);

		numberTf = new JTextField();
		panel_4.add(numberTf);
		numberTf.setColumns(25);

		JLabel lblNewLabel_7 = new JLabel("合计金额：");
		panel_4.add(lblNewLabel_7);

		priceTf = new JTextField();
		priceTf.setEditable(false);
		panel_4.add(priceTf);
		priceTf.setColumns(25);

		JLabel lblNewLabel_3 = new JLabel("结算方式：");
		panel_2.add(lblNewLabel_3);

		comboBox_1 = new JComboBox();
		comboBox_1.setModel(new DefaultComboBoxModel(new String[] { "现金", "银联刷卡", "转账" }));
		panel_2.add(comboBox_1);

		JLabel lblNewLabel_4 = new JLabel("进货时间：");
		panel_2.add(lblNewLabel_4);

		timeTf = new JTextField();
		timeTf.setEditable(false);
		panel_2.add(timeTf);
		timeTf.setColumns(25);

		JLabel lblNewLabel_5 = new JLabel("经手人：");
		panel_2.add(lblNewLabel_5);

		sponTf = new JTextField();
		panel_2.add(sponTf);
		sponTf.setColumns(25);
		panel_1.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

		JLabel lblNewLabel = new JLabel("进货单号：");
		panel_1.add(lblNewLabel);

		idTf = new JTextField();
		idTf.setEditable(false);
		panel_1.add(idTf);
		idTf.setColumns(25);

		JLabel lblNewLabel_1 = new JLabel("供应商：");
		panel_1.add(lblNewLabel_1);

		comboBox = new JComboBox();
		comboBox.setMaximumRowCount(25);
		comboBox.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				selectAction();
			}
		});
		panel_1.add(comboBox);

		JLabel lblNewLabel_2 = new JLabel("联系人：");
		panel_1.add(lblNewLabel_2);

		conTf = new JTextField();
		conTf.setEditable(false);
		panel_1.add(conTf);
		conTf.setColumns(25);
		panel.setLayout(gl_panel);
		providerService = CommonFactory.getProviderService();
		goodsService = CommonFactory.getGoodsService();
		inportService = CommonFactory.getInportService();
		initComboBox();
		// 设置操作者
		if (MainFrame.getLoginedUser() != null) {
			operTf.setText(MainFrame.getLoginedUser().getUsername());
		}

	}

	/**
	 * 初始供应商下拉选择框
	 */
	public void initComboBox() {
		// 获取数据库中的数据
		List<Provider> list = providerService.findProviders(null);
		// 设置下来列表框中数据模型
		Vector<Item> items = new Vector<>();
		// 清空下拉列表框中的内容，免的重复
		comboBox.removeAllItems();
		// 迭代处理数据
		for (int i = 0; i < list.size(); i++) {
			Item item = new Item();
			item.setId(list.get(i).getId());// 数据库要用
			item.setName(list.get(i).getCustomerName());// 界面展示用
			item.setContacts(list.get(i).getContacts());// 联系人
			if (items.contains(item)) {// 如果集合中包含该元素，就不在添加
				continue;
			}
			items.add(item);
			comboBox.addItem(item);
		}

		
	}

	/**
	 * 供应商下拉列表框点击事件
	 */
	private void selectAction() {

		if (!(comboBox.getSelectedItem() instanceof Item)) {
			return;
		}
		// 每选择一次，就更新一次Item
		providerItem = (Item) comboBox.getSelectedItem();
		System.out.println(providerItem.getId() + "," + providerItem.getName());
		// 更新联系人
		conTf.setText(providerItem.getContacts());
		// 更新表格
		GoodsInfo g = new GoodsInfo();
		g.setProviderId(providerItem.getId());
		updateAllData(g);
	}

	/**
	 * 更新表格数据
	 * 
	 * @param c
	 */
	private void updateAllData(GoodsInfo c) {
		// 查询数据库
		List<GoodsInfo> customers = goodsService.findGoods(c);
		if (customers != null) {
			Vector<GoodsInfo> list = new Vector<GoodsInfo>();
			for (GoodsInfo customer : customers) {
				list.add(customer);
			}
			// 更新数据
			tableModel.updateData(list);
			//table.setRowSelectionInterval(0, 0);// 表示选中第属一行//默认选中第一行
              table.setRowSelectionInterval(0, 0);
			// 如果没有做选择，将使用第一个默认价格
			// customers.get(0).getPrice();
		}
	}

	/**
	 * 点击事件
	 * 
	 * @param arg0
	 */
	@Override
	public void actionPerformed(ActionEvent e) {
		String target = e.getActionCommand();
		// 生成入库时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		float prices=0;//合计金额
		switch (target) {
		case "入库":
			checkNotNull();
            //处理日期
			Date time = null;
			try {
				//入库时间
				time = sdf.parse(timeTf.getText().trim());
			} catch (ParseException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			//处理价格
			prices = Float.parseFloat(priceTf.getText().trim());
			//封装数据
			InAndOut inport = new InAndOut(idTf.getText().trim(), Integer.parseInt(numberTf.getText().trim()), 
					prices, comTf.getText().trim(), 
					((Item)(comboBox.getSelectedItem())).getId(), time, 
					operTf.getText().trim(), sponTf.getText().trim(), 
					comboBox_1.getSelectedItem().toString(), goodsId);
			//入库
			boolean isFlag = inportService.saveInport(inport);
			if(isFlag==true) {
				JOptionPane.showMessageDialog(null, "入库信息添加成功！","提示",JOptionPane.INFORMATION_MESSAGE);
				setNull();
			}else {
				JOptionPane.showMessageDialog(null, "入库信息添加失败！","警告",JOptionPane.WARNING_MESSAGE);			
			}
			break;
		case "确认":
			if (numberTf.getText().trim() == null || numberTf.getText().trim().length() == 0) {
				JOptionPane.showMessageDialog(null, "商品数量不能为空！", "警告", JOptionPane.WARNING_MESSAGE);
				return;
			}
			if (sponTf.getText().trim() == null || sponTf.getText().trim().length() == 0) {
				JOptionPane.showMessageDialog(null, "经手人不能为空！", "警告", JOptionPane.WARNING_MESSAGE);
				return;
			}
			// 生成入库单号
			String id = inportService.getInportId();
			idTf.setText(id);
			String date = sdf.format(new Date());
			timeTf.setText(date);
			// 生成商品合计价格

			prices = price * Integer.parseInt(numberTf.getText().trim());
			priceTf.setText(prices + "");
		
			break;

		default:
			break;
		}

	}
    /**
     * 清空数据
     */
	private void setNull() {
		idTf.setText("");
		comboBox.setSelectedIndex(0);
		comboBox_1.setSelectedIndex(0);
		timeTf.setText("");
		sponTf.setText("");
		numberTf.setText("");
		priceTf.setText("");
		comTf.setText("");
		
	}

	/**
	 * 非空验证
	 */
	public void checkNotNull() {
		if (idTf.getText().trim() == null || idTf.getText().trim().length() == 0) {
			JOptionPane.showMessageDialog(null, "入库单号不能为空，请先确认！");
			return;
		}
		if (timeTf.getText().trim() == null || timeTf.getText().trim().length() == 0) {
			JOptionPane.showMessageDialog(null, "入库时间不能为空，请先确认！");
			return;
		}
		if (sponTf.getText().trim() == null || sponTf.getText().trim().length() == 0) {
			JOptionPane.showMessageDialog(null, "经手人不能为空！", "警告", JOptionPane.WARNING_MESSAGE);
			return;
		}
		if (numberTf.getText().trim() == null || numberTf.getText().trim().length() == 0) {
			JOptionPane.showMessageDialog(null, "商品数量不能为空！", "警告", JOptionPane.WARNING_MESSAGE);
			return;
		}
		if (priceTf.getText().trim() == null || priceTf.getText().trim().length() == 0) {
			JOptionPane.showMessageDialog(null, "合计金额不能为空，请先确认！");
			return;
		}
		if (comTf.getText().trim() == null || comTf.getText().trim().length() == 0) {
			JOptionPane.showMessageDialog(null, "验收结论不能为空！", "警告", JOptionPane.WARNING_MESSAGE);
			return;
		}
//		if (!ValidationManager.validateDate(timeTf.getText().trim())) {
//			JOptionPane.showMessageDialog(null, "日期输入有误！", "警告", JOptionPane.WARNING_MESSAGE);
//			return;
//		}

	}
	

}